package com.ihd.ihardwaretools.view.view;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ihd.ihardwaretools.R;
import com.ihd.ihardwaretools.common.AppConstans;
import com.ihd.ihardwaretools.common.utils.DataUtils;
import com.ihd.ihardwaretools.databinding.ActivityMainBinding;
import com.ihd.ihardwaretools.pojo.ListRes;
import com.ihd.ihardwaretools.pojo.OPValue;
import com.ihd.ihardwaretools.view.viewmodel.MainViewModel;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.picker.OptionPicker;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.wowjoy.commonlibrary.LiveDataBus.LiveDataBus;
import cn.wowjoy.commonlibrary.app.Constans;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.DateUtils;
import cn.wowjoy.commonlibrary.utils.DensityUtil;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.HexUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;
import cn.wowjoy.commonlibrary.widget.MPopupwindow;
import cn.wowjoy.commonlibrary.widget.titlebar.TitleBar;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {
    private int REQUEST_CODE_BLUETOOTH_ON = 100;
    //    private MPopupwindow mWhoPop;
    private MDialog mDG;
    private String originalData;

//    private String lsx;
//    private OptionPicker mLSXPicker;
//    private List<OPValue> lsxs = new ArrayList<>();

    private String dValue;
    private OptionPicker mDPicker;
    private List<OPValue> ds = new ArrayList<>();

    private int total = 0;
    private List<ListRes.DataBean.ListBean> ldls = new ArrayList<>();

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(false).init();

//        String token = SPUtils.getString(Constans.GATEWAY_TOKEN, "");
//        JsonObject jo = new JsonParser().parse(token).getAsJsonObject();
        binding.mtitlebar.setTitle("检测工具");
//        binding.mtitlebar.setTitle(jo.get("nickname").getAsString());
        binding.mtitlebar.setTitleColor(getResources().getColor(R.color.C_FFFFFF));
//        binding.mtitlebar.addAction(new TitleBar.Action() {
//            @Override
//            public String getText() {
//                return null;
//            }
//
//            @Override
//            public int getDrawable() {
//                return R.drawable.nbicon_more;
//            }
//
//            @Override
//            public void performAction(View view) {
//                mWhoPop.show(view);
//            }
//        });

//        mWhoPop = new MPopupwindow(this, viewModel.mWhoAdapter, DensityUtil.getWidthPixels() / 4, DensityUtil.dip2px(45));
//        viewModel.setActions();

//        LiveDataBus.get().with("1", Integer.class).observe(this, new Observer<Integer>() {
//            @Override
//            public void onChanged(@Nullable Integer type) {
//                mWhoPop.dismiss();
////                if (type == 0) {
////                    Intent i = new Intent(MainActivity.this, ChangeActivity.class);
////                    startActivity(i);
////                } else {
//                mDG = DialogUtils.alertDialog(MainActivity.this, "确定退出登录？", "取消", "确定", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        mDG.cancel();
//                    }
//                }, new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        mDG.cancel();
//                        SPUtils.removeAll();
//                        Intent i = new Intent(MainActivity.this, LoginActivity.class);
//                        startActivity(i);
//                        finish();
//                    }
//                });
////                }
//            }
//        });

        binding.mjRV.setAdapter(viewModel.mConcernedAdapter);
//        lsxs.add(new OPValue("A线"));
//        lsxs.add(new OPValue("B线"));
//        lsxs.add(new OPValue("C线"));
//        lsxs.add(new OPValue("D线"));
//        mLSXPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
//            @Override
//            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
//                binding.lsxCode.setText(lsxs.get(selectedPosition[0]).getValue());
//                lsx = lsxs.get(selectedPosition[0]).getValue();
//                SPUtils.putString("LSX", lsx);
//            }
//        }).create();
//
//        lsx = SPUtils.getString("LSX", "A线");
//        binding.lsxCode.setText(lsx);
//        mLSXPicker.setDataWithValues(lsxs, lsx);
//        binding.lsxCode.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mLSXPicker.show();
//            }
//        });

        for (int i = 0; i >= -99; i--) {
            ds.add(new OPValue(String.valueOf(i)));
        }
        mDPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
            @Override
            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
                binding.distance.setText(ds.get(selectedPosition[0]).getValue());
                dValue = ds.get(selectedPosition[0]).getValue();
                SPUtils.putString("DVALUE", dValue);
            }
        }).create();

        dValue = SPUtils.getString("DVALUE", "-80");
        binding.distance.setText(dValue);
        mDPicker.setDataWithValues(ds, dValue);
        binding.distance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDPicker.show();
            }
        });

        binding.khCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDG = DialogUtils.inputDialog(MainActivity.this, "客户编码", "请输入编码".equals(binding.khCode.getText().toString()) ? "" : binding.khCode.getText().toString());
                mDG.setMsgCallback(new MDialog.interfaceEdit() {
                    @Override
                    public void Receive(String message) {
                        binding.khCode.setText(TextUtils.isEmpty(message) ? "请输入编码" : message);
                    }
                });
            }
        });

//        setRx(AppConstans.LIST, new BaseConsumer<ListRes>() {
//            @Override
//            protected void onStart() {
//            }
//
//            @Override
//            protected void onSuccess(ListRes mLiveData) {
//                viewModel.setList(mLiveData.getData().getList());
//                binding.total.setText(mLiveData.getData().getTotal());
//                total++;
//                binding.singleNum.setText(String.valueOf(total));
//            }
//
//            @Override
//            protected void onError(Throwable error) {
//                ToastUtils.showShort(MainActivity.this, error.getMessage());
//            }
//        });

//        viewModel.list(1, 100, "", "");

        if (!BLEUtils.getInstance().isBluetoothOpened()) {
            Intent requestBluetoothOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON);
        } else
            connectBluetooth();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected Class getViewModelClass() {
        return MainViewModel.class;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    connectBluetooth();
                    break;
                case Activity.RESULT_CANCELED:
                    ToastUtils.showLong(this, "请手动打开蓝牙再进入app，才能获取数据哦~");
                    break;
                default:
                    break;
            }
        }
    }

    private void connectBluetooth() {
        BLEUtils.getInstance().search(new SearchRequest.Builder().searchBluetoothLeDevice(86400000).build(), new SearchResponse() {
            @Override
            public void onSearchStarted() {
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                if (Integer.parseInt(dValue) <= device.rssi) {
                    Beacon beacon = new Beacon(device.scanRecord);
                    byte[] mByte = new byte[31];
                    System.arraycopy(beacon.mBytes, 0, mByte, 0, beacon.mBytes.length);
                    if (DataUtils.isValidDevice(mByte) && DataUtils.isStable(mByte)) {
                        String data = HexUtils.bytesToHex(mByte);
                        if (!data.equals(originalData)) {
                            originalData = data;
                            binding.weight.setText(DataUtils.getWeight(mByte) + "KG");
                            binding.dzlTV.setText(DataUtils.getOmu(mByte) + "Ω");
//                            if ("请输入编码".equals(binding.khCode.getText().toString()))
//                                ToastUtils.showLong(MainActivity.this, "请填写客户编码");
//                            else
//                            viewModel.bind(originalData, "0", lsx);
                            ListRes.DataBean.ListBean ldl = new ListRes.DataBean.ListBean();
                            ldl.setMac(DataUtils.getMacAddress(mByte));
                            ldl.setModifyTime(DateUtils.getCurrFullTime());
                            ldls.add(0, ldl);
                            viewModel.setList(ldls);
                            total++;
                            binding.total.setText(String.valueOf(total));
                            binding.singleNum.setText(String.valueOf(total));
                        }
                    }
                }
            }

            @Override
            public void onSearchStopped() {
            }

            @Override
            public void onSearchCanceled() {
            }
        });
    }

    @Override
    protected void onDestroy() {
        BLEUtils.getInstance().stopSearch();
        super.onDestroy();
    }
}
